// ============ AI工具调度系统 - 类型定义 ============

/**
 * 工具定义接口
 */
export interface ToolDefinition {
  id: string;
  name: string;
  description: string;
  parameters: Record<string, any>; // JSON Schema
  handler: ToolHandler;
  metadata?: {
    timeout?: number; // 超时(ms)，默认 30000
    category?: string;
    tags?: string[];
  };
}

/**
 * 工具执行请求
 */
export interface ToolExecutionRequest {
  toolId: string;
  parameters: Record<string, any>;
  metadata?: {
    requestId?: string;
    timeout?: number;
    signal?: AbortSignal;
  };
}

/**
 * 工具执行结果
 */
export interface ToolExecutionResult {
  success: boolean;
  data?: any;
  error?: string;
  errorType?: 'cancelled' | 'timeout' | 'error';
  metadata?: {
    executionTime: number;
    fromCache?: boolean;
  };
}

/**
 * 工具执行任务
 */
export interface ToolExecutionTask {
  id: string;
  toolId: string;
  parameters: Record<string, any>;
  status: 'pending' | 'running' | 'completed' | 'error' | 'cancelled';
  startTime?: number;
  endTime?: number;
  result?: ToolExecutionResult;
  abortController?: AbortController;
}

/**
 * 工具处理函数类型
 */
export type ToolHandler = (
  parameters: Record<string, any>, 
  context: { signal?: AbortSignal }
) => Promise<any>;

/**
 * 多轮工具调用选项
 */
export interface OrchestrationOptions {
  maxRounds?: number;        // 最大轮次，默认 100
  enableMultiRound?: boolean; // 是否启用多轮，默认 true
  abortSignal?: AbortSignal; // 中断信号
  onRoundComplete?: (round: number, toolResults: any[]) => void; // 轮次完成回调
  onMessageUpdate?: (updatedMessages: any[]) => void; // 实时消息更新回调
  onAssistantResponse?: (response: string) => void; // AI 响应回调
  onToolCallStart?: (round: number, toolCalls: any[]) => void; // 工具调用开始回调
}

/**
 * 多轮工具调用结果
 */
export interface OrchestrationResult {
  hasToolCalls: boolean; 
  updatedMessages?: Array<{ role: string; content: string; [key: string]: any }>;
  totalRounds?: number;
  finalResponse?: string;
}

/**
 * 工具查询过滤器
 */
export interface ToolQueryFilter {
  category?: string;
  tags?: string[];
  name?: string;
}

/**
 * 工具执行上下文
 */
export interface ToolExecutionContext {
  signal?: AbortSignal;
}

/**
 * 聊天消息接口
 */
export interface ChatMessage {
  role: string;
  content: string;
  [key: string]: any;
}

/**
 * 工具调用响应接口
 */
export interface ToolCallResponse {
  tool_call_id?: string;
  role: 'tool';
  name?: string;
  content: string;
}